<?php

class Ext_Model_PLSqlProcedure {

    protected $_owner = null;
    protected $_package = null;
    protected $_db = null;

    function __construct( Zend_Db_Adapter_Abstract $db, $package = null ) {
        $this->_db = $db;
        $this->_package = $package;
    }

    function  __call($name, $args) {
        if ( empty( $this->_package ) ) {
            throw new Exception( "invalid package name" );
        }

        if ( ! is_array( $args[ 0 ] ) ) {
            throw new Exception( "PLSQL calls must be done with arrays" );
        }

        $name = $this->_package . "." . $name;
        if ( ! empty( $this->_owner ) ) {
            $name = $this->_owner  . "." . $name;
        }

        $params = array();
        foreach( $args[0] as $k => $v ) {
            $params[] = ":$k";
        }
        $params = implode(',', $params);
        $sql = "begin $name ( $params ); end;";
        $statement = new Zend_Db_Statement_Oracle( $this->_db, $sql );
        $statement->execute( $args[0] );
        return $args[ 0 ];
    }

/*
 TODO: Ver como extraer los datos que vienen por un ref-cursor.

    // Use ref cursor to fetch employee records
    // All records are retrieved - there is no paging in this example
    function db_get_employees_rc($conn, $deptid, &$e)
    {
      // Execute the call to the stored procedure
      $stmt = "BEGIN cv_types.get_employees($deptid, :rc); END;";
      $stid = @oci_parse($conn, $stmt);
      if (!$stid) {
        $e = db_error($conn, __FILE__, __LINE__);
        return false;
      }
      $refcur = oci_new_cursor($conn);
      if (!$stid) {
        $e = db_error($conn, __FILE__, __LINE__);
        return false;
      }
      $r = @oci_bind_by_name($stid, ':RC', $refcur, -1, OCI_B_CURSOR);
      if (!$r) {
        $e = db_error($stid, __FILE__, __LINE__);
        return false;
      }
      $r = @oci_execute($stid);
      if (!$r) {
        $e = db_error($stid, __FILE__, __LINE__);
        return false;
      }
      // Now treat the ref cursor as a statement resource
      $r = @oci_execute($refcur, OCI_DEFAULT);
      if (!$r) {
        $e = db_error($refcur, __FILE__, __LINE__);
        return false;
      }
      $r = @oci_fetch_all($refcur, $employeerecords, null, null,
                          OCI_FETCHSTATEMENT_BY_ROW);
      if (!$r) {
        $e = db_error($refcur, __FILE__, __LINE__);
        return false;
      }
      return ($employeerecords);
    }

 */
    public function getPackage() {
        return $this->_package;
    }

    public function setPackage($_package) {
        $this->_package = $_package;
    }

    public function getDb() {
        return $this->_db;
    }

    public function setDb($_db) {
        $this->_db = $_db;
    }

    public function getOwner() {
        return $this->_owner;
    }

    public function setOwner($_owner) {
        $this->_owner = $_owner;
    }



}
